# -*- coding: utf-8 -*-
import os

from devicetest.core.test_case import TestCase, Step, CheckPoint
from xdevice import platform_logger
from aw.Common import BuildFunctions

log = platform_logger('Preload')


class CompileTestLeveL301(TestCase):
    def __init__(self, configs):
        self.TAG = self.__class__.__name__
        self.tests = ['test_step']
        TestCase.__init__(self, self.TAG, configs)

    def setup(self):
        pass

    def test_step(self):
        hvigorw_path = r"E:\commandline-tools-windows-x64-5.0.5.310\command-line-tools\bin"
        hvigorw_cmd = os.path.join(hvigorw_path, "hvigorw")
        COMPILE_CMD = (
            f'"{hvigorw_cmd}" --mode module -p module=entry@default '
            '-p product=default -p requiredDeviceType=phone assembleHap --analyze=normal '
            '--parallel --incremental --no-daemon'
        )
        current_dir = os.getcwd()
        parent_dir = os.path.dirname(current_dir)
        # 构建 projects 目录的路径
        projects_dir = os.path.join(parent_dir, 'projects')
        failed_num = 0
        success_num = 0
        # 检查 projects dir is exists
        if not os.path.exists(projects_dir):
            log.info(f"Directory '{projects_dir}' does not exist.")
        else:
            # 遍历 projects 目录中的所有子文件夹
            for entry in os.scandir(projects_dir):
                if entry.is_dir():
                    compile_dir = os.path.join(projects_dir, entry.name)
                    out = BuildFunctions.run_cmd(COMPILE_CMD, compile_dir)
                    return_code, stdout, stderr = out
                    print(stderr)
                    if return_code == 0:
                        success_num += 1
                    else:
                        failed_num += 1
        print('======================compile success total num', success_num)
        print('======================compile failed total num', failed_num)

    def teardown(self):
        pass
